package com.cucn.ingmall.product.service.impl;

import com.alibaba.fastjson.TypeReference;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.cucn.common.constant.product.ProductConstant;
import com.cucn.common.to.SkuHasStockVO;
import com.cucn.common.to.SkuReductionTO;
import com.cucn.common.to.SpuBoundsTO;
import com.cucn.common.to.es.SkuEsModel;
import com.cucn.common.utils.PageUtils;
import com.cucn.common.utils.Query;
import com.cucn.common.utils.R;
import com.cucn.ingmall.product.dao.SpuInfoDao;
import com.cucn.ingmall.product.entity.*;
import com.cucn.ingmall.product.feign.CouponFeignService;
import com.cucn.ingmall.product.feign.SearchFeignService;
import com.cucn.ingmall.product.feign.WareFeignService;
import com.cucn.ingmall.product.service.*;
import com.cucn.ingmall.product.vo.*;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang.StringUtils;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import javax.annotation.Resource;
import java.math.BigDecimal;
import java.util.HashSet;
import java.util.List;
import java.util.Map;
import java.util.Set;
import java.util.stream.Collectors;

/**
 * spu信息
 *
 * @author kouchaojie
 * @email kou1688@foxmail.com
 * @date 2021-11-17 16:27:03
 */
@Slf4j
@Service("spuInfoService")
public class SpuInfoServiceImpl extends ServiceImpl<SpuInfoDao, SpuInfoEntity> implements SpuInfoService {
    @Autowired
    private SpuInfoDescService spuInfoDescService;

    @Autowired
    private SpuImagesService spuImagesService;

    @Autowired
    private ProductAttrValueService productAttrValueService;

    @Autowired
    private AttrService attrService;

    @Autowired
    private SkuInfoService skuInfoService;

    @Autowired
    private SkuImagesService skuImagesService;

    @Autowired
    private SkuSaleAttrValueService skuSaleAttrValueService;

    @Autowired
    private CouponFeignService couponFeignService;

    @Autowired
    private BrandService brandService;

    @Autowired
    private CategoryService categoryService;

    @Autowired
    private WareFeignService wareFeignService;

    @Autowired
    private SearchFeignService searchFeignService;

    @Resource
    private SpuInfoDao spuInfoDao;

    @Override
    public PageUtils queryPage(Map<String, Object> params) {
        IPage<SpuInfoEntity> page = this.page(
                new Query<SpuInfoEntity>().getPage(params),
                new QueryWrapper<SpuInfoEntity>()
        );

        return new PageUtils(page);
    }

    /**
     * 新增商品
     * 使用seata的AT分布式事务
     *
     * @param spuSaveVO 新增商品的信息
     */
    @Override
    @Transactional
    public void saveSpuInfo(SpuSaveVO spuSaveVO) {

        //1.保存SPU基本信息 pms_spu_info
        SpuInfoEntity spuInfoEntity = new SpuInfoEntity();
        BeanUtils.copyProperties(spuSaveVO, spuInfoEntity);
        this.saveBaseSpuInfo(spuInfoEntity);

        //2.保存spu的描述图片 pms_spu_info_desc
        List<String> decript = spuSaveVO.getDecript();
        SpuInfoDescEntity spuInfoDescEntity = new SpuInfoDescEntity();
        spuInfoDescEntity.setSpuId(spuInfoEntity.getId());
        spuInfoDescEntity.setDecript(String.join(",", decript));
        spuInfoDescService.save(spuInfoDescEntity);

        //3.保存spu的图片集 pms_spu_images
        List<String> spuImages = spuSaveVO.getImages();
        spuImagesService.saveSpuImages(spuInfoEntity.getId(), spuImages);

        //4.保存spu的规格参数 pms_product_attr_value
        List<BaseAttrs> baseAttrs = spuSaveVO.getBaseAttrs();
        List<ProductAttrValueEntity> productAttrValueList = baseAttrs.stream().map(baseAttr -> {
            ProductAttrValueEntity productAttrValueEntity = new ProductAttrValueEntity();
            productAttrValueEntity.setAttrId(baseAttr.getAttrId());
            productAttrValueEntity.setSpuId(spuInfoEntity.getId());
            productAttrValueEntity.setAttrName(attrService.getById(productAttrValueEntity.getAttrId()).getAttrName());
            productAttrValueEntity.setAttrValue(baseAttr.getAttrValues());
            productAttrValueEntity.setQuickShow(baseAttr.getShowDesc());
            return productAttrValueEntity;
        }).collect(Collectors.toList());
        productAttrValueService.saveProductAttr(productAttrValueList);

        //5.保存spu的积分信息 跨库 sms_spu_bounds 商品积分
        Bounds bounds = spuSaveVO.getBounds();
        SpuBoundsTO spuBoundsTO = new SpuBoundsTO();
        BeanUtils.copyProperties(bounds, spuBoundsTO);
        spuBoundsTO.setSpuId(spuInfoEntity.getId());
        R r1 = couponFeignService.saveSpuBounds(spuBoundsTO);
        if (r1.getCode() != 0) {
            log.error("远程保存spu积分信息失败!");
        }

        //6.保存当前spu对应的所有sku信息:
        //6.1 sku的基本信息 pms_sku_info
        List<Skus> skus = spuSaveVO.getSkus();
        skus.forEach(item -> {
            //获取sku图集
            List<Images> images = item.getImages();
            //获取sku图集里的默认图片
            String defaultImg = "";
            for (Images image : images) {
                if (image.getDefaultImg() == 1) {
                    defaultImg = image.getImgUrl();
                }
            }

            SkuInfoEntity skuInfoEntity = new SkuInfoEntity();
            //private String skuName;
            //private BigDecimal price;
            //private String skuTitle;
            // private String skuSubtitle;
            BeanUtils.copyProperties(item, skuInfoEntity);
            skuInfoEntity.setSpuId(spuInfoEntity.getId());
            skuInfoEntity.setBrandId(spuInfoEntity.getBrandId());
            skuInfoEntity.setCatalogId(spuInfoEntity.getCatalogId());
            skuInfoEntity.setSaleCount(0L);
            skuInfoEntity.setSkuDefaultImg(defaultImg);
            skuInfoEntity.setSkuDesc(String.join(",", item.getDescar()));
            skuInfoService.saveSkuInfo(skuInfoEntity);

            Long skuId = skuInfoEntity.getSkuId();

            //6.2 sku的图片信息 pms_sku_images
            List<SkuImagesEntity> skuImagesList = images.stream().map(img -> {
                SkuImagesEntity skuImagesEntity = new SkuImagesEntity();
                skuImagesEntity.setSkuId(skuId);
                skuImagesEntity.setImgUrl(img.getImgUrl());
                skuImagesEntity.setDefaultImg(img.getDefaultImg());

                return skuImagesEntity;
            }).filter(entity -> {
                return !StringUtils.isEmpty(entity.getImgUrl());
            }).collect(Collectors.toList());
            skuImagesService.saveBatch(skuImagesList);

            //6.3 sku的销售属性信息 pms_sku_sale_attr_value
            List<Attr> attrList = item.getAttr();
            List<SkuSaleAttrValueEntity> skuSaleAttrValueList = attrList.stream().map(attr -> {
                SkuSaleAttrValueEntity attrValueEntity = new SkuSaleAttrValueEntity();
                BeanUtils.copyProperties(attr, attrValueEntity);
                attrValueEntity.setSkuId(skuInfoEntity.getSkuId());
                return attrValueEntity;
            }).collect(Collectors.toList());
            skuSaleAttrValueService.saveBatch(skuSaleAttrValueList);

            //6.4 sku的优惠与满减等信息 跨库 ingmall_sms sms_sku_ladder(商品阶梯价格(打折))
            //sms_sku_full_reduction 商品满减表
            //sms_member_price 商品会员价格
            SkuReductionTO skuReductionTO = new SkuReductionTO();
            BeanUtils.copyProperties(item, skuReductionTO);
            skuReductionTO.setSkuId(skuId);
            if (skuReductionTO.getFullCount() > 0 || skuReductionTO.getFullPrice().compareTo(new BigDecimal("0")) > 0) {
                R r = couponFeignService.saveSkuReduction(skuReductionTO);
                if (r.getCode() != 0) {
                    log.error("远程保存sku优惠信息失败!");
                }
            }

        });

    }

    /**
     * 保存Spu的基本信息
     *
     * @param spuInfoEntity spu基础信息对象
     */
    @Override
    public void saveBaseSpuInfo(SpuInfoEntity spuInfoEntity) {
        this.save(spuInfoEntity);
    }

    /**
     * SPU条件检索
     *
     * @param params 请求参数
     * @return 查询出的分页数据
     */
    @Override
    public PageUtils queryPageByCondition(Map<String, Object> params) {
        QueryWrapper<SpuInfoEntity> wrapper = new QueryWrapper<>();
        /**
         * key: '华为',//检索关键字
         *    catelogId: 6,//三级分类id
         *    brandId: 1,//品牌id
         *    status: 0,//商品状态
         */
        String key = (String) (params.get("key"));
        if (StringUtils.isNotEmpty(key)) {
            wrapper.and(w -> {
                w.eq("id", key).or().like("spu_name", key);
            });
        }

        String catelogId = (String) (params.get("catelogId"));
        if (StringUtils.isNotEmpty(catelogId) && !"0".equalsIgnoreCase(catelogId)) {
            wrapper.eq("catalog_id", catelogId);
        }

        String brandId = (String) (params.get("brandId"));
        if (StringUtils.isNotEmpty(brandId) && !"0".equalsIgnoreCase(brandId)) {
            wrapper.eq("brand_id", brandId);
        }

        String status = (String) (params.get("status"));
        if (StringUtils.isNotEmpty(status)) {
            wrapper.eq("publish_status", status);
        }

        IPage<SpuInfoEntity> page = this.page(
                new Query<SpuInfoEntity>().getPage(params),
                wrapper
        );

        return new PageUtils(page);
    }

    /**
     * 商品上架
     *
     * @param spuId spuId
     */
    @Override
    public void up(Long spuId) {
        //查出当前spuId对应的所有sku信息,品牌名称
        List<SkuInfoEntity> skuInfoList = skuInfoService.list(new QueryWrapper<SkuInfoEntity>().eq("spu_id", spuId));
        //获取spu对应的品牌信息
        BrandEntity spuBrandInfo = this.getSpuBrandInfo(spuId);
        //获取spu对应的分类信息
        SpuInfoEntity spuInfo = this.getById(spuId);
        CategoryEntity spuCategoryInfo = categoryService.getById(spuInfo.getCatalogId());

        //查出当前sku所有可以被检索的属性
        List<ProductAttrValueEntity> productAttrValueList = productAttrValueService.getBySpuId(spuId);
        List<Long> attrIdList = productAttrValueList.stream().map(item -> {
            return item.getAttrId();
        }).collect(Collectors.toList());
        //查出所有可被检索的属性id
        List<Long> searchAttrIdList = attrService.selectSearchAttrIds(attrIdList);

        Set<Long> attrIds = new HashSet<>(searchAttrIdList);
        //最终封装的属性信息
        //过滤出可以被检索的属性
        List<SkuEsModel.Attrs> finalAttrs = productAttrValueList.stream().filter(item -> {
            return attrIds.contains(item.getAttrId());
        }).map(item -> {
            SkuEsModel.Attrs attr = new SkuEsModel.Attrs();
            BeanUtils.copyProperties(item, attr);
            return attr;
        }).collect(Collectors.toList());

        //获取所有spu对应的skuId
        List<Long> skuIds = skuInfoList.stream().map(SkuInfoEntity::getSkuId).collect(Collectors.toList());

        //发送远程调用,查询是否有库存,有可能会失败,catch
        Map<Long, Boolean> hasStockMap = null;
        try {
            R r = wareFeignService.getSkusHasStock(skuIds);
            //转成map
            TypeReference<List<SkuHasStockVO>> typeReference = new TypeReference<List<SkuHasStockVO>>() {
            };
            hasStockMap = r.getData(typeReference).stream().collect(Collectors.toMap(SkuHasStockVO::getSkuId, SkuHasStockVO::getHasStock));
        } catch (Exception e) {
            log.error("库存服务查询异常:{}", e);
        }

        Map<Long, Boolean> finalHasStockMap = hasStockMap;
        List<SkuEsModel> upProducts = skuInfoList.stream().map(item -> {
            //组装需要的数据
            SkuEsModel esModel = new SkuEsModel();
            BeanUtils.copyProperties(item, esModel);
            //skuPrice,skuImg,hasStock,hotScore,brandName,brandImg,catalogName,attrs{attrId,attrName,attrValue}
            esModel.setSkuPrice(item.getPrice());
            esModel.setSkuImg(item.getSkuDefaultImg());

            //设置库存信息
            if (finalHasStockMap == null) {
                esModel.setHasStock(true);
            } else {
                esModel.setHasStock(finalHasStockMap.get(item.getSkuId()));
            }

            //热度评分.0
            esModel.setHotScore(0L);

            //品牌信息,分类信息
            esModel.setBrandName(spuBrandInfo.getName());
            esModel.setBrandImg(spuBrandInfo.getLogo());
            esModel.setCatalogName(spuCategoryInfo.getName());

            //sku属性
            esModel.setAttrs(finalAttrs);

            return esModel;
        }).collect(Collectors.toList());

        //KouTODO:2021/12/10 14:22 Kou 将数据发送给ElasticSearch进行保存(发送给ingmall-search)
        R r = searchFeignService.productStatusUp(upProducts);
        if (r.getCode() == 0) {
            //远程调用成功
            //修改当前spu的状态
            this.baseMapper.updateSpuStatus(spuId, ProductConstant.SpuPublishStatusEnum.SPU_UP.getCode());
        } else {
            log.info("商品上架失败");
            //远程调用失败
            //KouTODO:2021/12/13 11:38 Kou 重复调用问题?接口幂等性;重试机制

            //Feign的调用流程？
            /*
            1.构造请求数据，将对象转为json
            2.发送请求进行执行(执行成功会解码响应数据)
            3.
             */
        }
    }

    /**
     * 获取spu的品牌名
     *
     * @param spuId spuId
     * @return spu对应的品牌名
     */
    @Override
    public BrandEntity getSpuBrandInfo(Long spuId) {
        SpuInfoEntity spuInfo = this.getById(spuId);
        Long brandId = spuInfo.getBrandId();
        return brandService.getById(brandId);
    }

    /**
     * 根据skuId获取对应的spu信息
     *
     * @return
     */
    @Override
    public SpuInfoEntity getSpuInfoBySkuId(Long skuId) {
        SkuInfoEntity skuInfo = skuInfoService.getById(skuId);
        Long spuId = skuInfo.getSpuId();

        return spuInfoDao.selectById(spuId);
    }
}